//用于分组试题，和收集题型
import {ref, onMounted, watch} from 'vue'
import {group_sort_rule} from "@/components/Picker/composables/config";

export default function use_grouping(subjects) {
    /*groups是一个对象{type_code:[idx_in_list,... ],type_code2:[idx_in_list,... ]}
      type_code对应的数组里面保存了subject_li中的原始索引
      all_types是保存了所有类型的数组[{type_code: 'radio', type_name: '单项选择题'},...]
      all_types是根据group_sort_rule题型分组排序依据排序好的*/
    const groups = ref({})
    const all_types = ref([])
    //对all_types根据分组排序规则进行排序的函数
    const all_types_sort = () => {
        all_types.value.sort((a, b) => {
            const a_index = group_sort_rule.indexOf(a['type_name'])
            const b_index = group_sort_rule.indexOf(b['type_name'])
            return a_index - b_index
        })
    }
    //对试题进行分组，并且收集所有题型
    const grouping = () => {
        [all_types.value, groups.value] = [[], {}]//置空所有内容
        for (let idx_in_list in subjects.value) {
            const subject = subjects.value[idx_in_list * 1]
            const type_code = String(subject.type_code)//转成字符串
            if (!groups.value[type_code]) {
                all_types.value.push({'type_code': type_code, 'type_name': subject.type_name})
            }
            groups.value[type_code] = groups.value[type_code] || []
            groups.value[type_code].push(idx_in_list * 1)//push原始索引
        }
        // all_types_sort()
    }
    onMounted(grouping)
    watch(subjects, grouping)
    return {
        groups,
        all_types
    }
}